package com.controller;

import com.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class UserController {

    @RequiresRoles(value = "管理员")
    @RequiresPermissions(value = {"sys:user:add", "sys:role:add"},logical = Logical.OR)
    @RequestMapping("/add")
    public Result add() {
        System.out.println("新增");
        return null;
    }

    @RequiresPermissions(value = "sys:role:edit")
    @RequestMapping("/edit")
    public Result edit() {
        System.out.println("编辑");
        return null;
    }

    @RequiresGuest
    @RequestMapping("/del")
    public Result del(){
        System.out.println("删除");
        return null;
    }

    @RequestMapping("/doLogin")
    public Result login(String username , String password, boolean rememberMe) {
        try {
            Subject subject = SecurityUtils.getSubject();

            Md5Hash md5Hash = new Md5Hash(password,username,  1024);

            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());
            if(rememberMe){
                token.setRememberMe(true);
            }

            subject.login(token);


            System.out.println("是否有管理员角色:"+ subject.hasRole("管理员"));
            System.out.println("是否有新增用户权限:"+ subject.isPermitted("sys:user:add"));

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return Result.error("未知的用户");
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return Result.error("账户已锁定");
        } catch (CredentialsException e) {
            e.printStackTrace();
            return Result.error("密码错误");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error("用户名不能为空");
        }
        return Result.ok("登录成功");

    }

    /**
     * 退出
     * @param mv
     * @return
     */
    @RequestMapping("/logout1")
    public ModelAndView logout(ModelAndView mv) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        mv.setViewName("redirect:/login.html");
        return mv;
    }
}